<!-- pages/register/register.vue -->
<template>
    <view class="container">
        <view class="form">
            <uni-forms ref="baseForm" :model="baseFormData">
                <uni-forms-item label="用户名" required>
                    <uni-easyinput v-model="baseFormData.userName" placeholder="请输入用户名" :maxlength="4" />
                </uni-forms-item>
                
                <uni-forms-item label="手机号">
                    <view class="info-text underline">{{baseFormData.phone}}</view>
                </uni-forms-item>
                <uni-forms-item label="金币">
                    <view class="info-text underline">{{baseFormData.amount}}</view>
                </uni-forms-item>
                
                <uni-forms-item label="微信收款码">
                    <view class="upload-container">
                        <image v-if="wxImg" 
                               :src="`${$baseUrl}/image/getImageById/${baseFormData.wechatQrCode}`" 
                               mode="aspectFit" 
                               class="preview-image" />
                        <view v-else class="upload-area" @click="uploadImage('wechat')">
                            <view class="plus-icon"></view>
                        </view>
                    </view>
                </uni-forms-item>
                
                <uni-forms-item label="支付宝收款码">
                    <view class="upload-container">
                        <image v-if="apImg" 
                               :src="`${$baseUrl}/image/getImageById/${baseFormData.alipayQrCode}`" 
                               mode="aspectFit" 
                               class="preview-image" />
                        <view v-else class="upload-area" @click="uploadImage('alipay')">
                            <view class="plus-icon"></view>
                        </view>
                    </view>
                </uni-forms-item>
                <uni-forms-item label="邮箱">
                    <uni-easyinput v-model="baseFormData.email" placeholder="请输入邮箱" />
                </uni-forms-item>
                
                <uni-forms-item label="QQ号">
                    <uni-easyinput v-model="baseFormData.qq" placeholder="请输入QQ号" />
                </uni-forms-item>
                
                <button class="zc" type="primary" @click="register">提交</button>
            </uni-forms>
        </view>
    </view>
</template>
<script>
export default {
    data() {
        return {
			wxImg: false,
			apImg: false,
            baseFormData: {
            },
            userNameErrorMessage: '',
            phoneErrorMessage: '',
            passwordErrorMessage: '',
            phoneRules: [
                {
                    required: true,
                    message: '手机号不能为空',
                    trigger: 'blur'
                },
                {
                    pattern: /^1[3-9]\d{9}$/,
                    message: '请输入正确的手机号码格式',
                    trigger: 'blur'
                }
            ],
			phone:'',
            countdown: 0, // 倒计时初始值
            isDisabled: false, // 按钮是否禁用
            countdownText: '获取验证码' // 按钮初始文字
        };
    },
	onLoad() {
		this.phone = uni.getStorageSync("phone")
		this.getUserInfo()
		// this.baseFormData.userName = user.userName
		// this.baseFormData.id = user.id
		// this.baseFormData.password = user.password
	},
    methods: {
		getUserInfo(){
			this.$myRequest({
			  	method: 'get',
			  	url: '/sysUser/getUserInfoByPhone',
				data:{phone:this.phone}
			  }).then((res) => {
				  if(res.flag){
					   this.baseFormData = res.data
					   if(this.baseFormData.wechatQrCode&&this.baseFormData.wechatQrCode!=0){
						   this.wxImg = true
					   }
					   if(this.baseFormData.alipayQrCode&&this.baseFormData.alipayQrCode!=0){
							this.apImg = true
}				  		}
			})
		},
        validateUserName() {
            if (this.baseFormData.userName.length > 4 || !/^[一-龥]{1,4}$/.test(this.baseFormData.userName)) {
                uni.showToast({
                    title: '用户名只能是四位数的汉字',
                    icon: 'none'
                });
                return false;
            } else {
                this.userNameErrorMessage = '';
            }
            return true;
        },
        verification() {
            this.chekPhone();
            let data = {
                phone: this.baseFormData.phone
            };
            this.$myRequest({
                method: 'get',
                url: '/sysUser/getRegisterCode',
                data: data
            }).then((res) => {
				// 设置倒计时时间
                this.serverCaptcha = res.data; // 将后端返回的值存储到一个新的变量 serverCaptcha 中
				uni.showToast({
				    title: '获取验证码成功！',
				    icon: 'none'
				});
				this.getCaptcha(); // 开始倒计时
            });
        },
        chekPhone() {
            // 验证手机号格式
            const valid = this.baseFormData.phone.match(/^1[3-9]\d{9}$/);
            if (!valid) {
                uni.showToast({
                    title: '请输入正确的手机号码格式',
                    icon: 'none'
                });
                // 重置相关数据
                this.baseFormData.phone = '';
                return false;
            }
            return true;
        },
        getCaptcha() {
			this.countdown = 60; 
            let interval = setInterval(() => {
                this.countdown--;
                if (this.countdown <= 0) {
                    clearInterval(interval);
                    this.countdown = 0;
                    // 倒计时结束后启用获取验��码按钮
                    this.isDisabled = false;
                }
            }, 1000);
        },
        comparisonCode() {
            // 在这里比较用户输入的验证码和后端返回的验证码
            if (this.baseFormData.captcha != this.serverCaptcha) {
                console.log(this.serverCaptcha);
                uni.showToast({
                    title: '验证码有误，请重新输入',
                    icon: 'none'
                });
                return false;
            }
            return true;
        },
        validatePassword() {
            if (this.baseFormData.password.length < 6 || /\s/.test(this.baseFormData.password) || !/^[a-zA-Z0-9]+$/.test(this.baseFormData.password)) {
                uni.showToast({
                    title: '密码需要大于 6 位，且只能包含数字和字母，不能有空格',
                    icon: 'none'
                });
                return false;
            }
            return true;
        },
        register() {
			let f4 = this.validateUserName();  // 用户名校验
			if (!f4) {
			    return;
			}
			// let f3 = this.chekPhone(); // 手机号校验
			// if (!f3) {
			//     return;
			// }
            // let f = this.validatePassword(); // 密码校验
            // if (!f) {
            //     return;
            // }
           
            this.$myRequest({
                method: 'PUT',
                url: '/sysUser/updateUser',
                data: this.baseFormData
				}).then(res => {
					if(res.flag){
						uni.showToast({
						    title: '修改成功！',
						    icon: 'none'
						});
						//const deviceId = uni.getSystemInfoSync().deviceId;
						// uni.setStorageSync("phone",this.baseFormData.phone)
						// setTimeout(function() {
						// 	uni.navigateTo({
						// 		url: '/pages/login/login'
						// 	});
						// },1000)
					}else{
						uni.showToast({
							title: res.data.errMsg,
						});
					}
                   
                })
        },
        uploadImage(type) {
            let that = this; // 保存 this 引用
            uni.chooseImage({
                count: 1,
				  sizeType: ['original', 'compressed'], // 可以选择原图或压缩图
				  sourceType: ['album', 'camera'], // 选择图片的来源，可以是相册和相机
                success: (chooseImageRes) => {
                    const tempFilePaths = chooseImageRes.tempFilePaths;
                    uni.uploadFile({
                        url: `${that.$baseUrl}/image/uploadFile/{cp}`, // 使用正确的上传接口
                        filePath: tempFilePaths[0],
                        name: 'file',
                        success: (uploadFileRes) => {
                            const responseData = JSON.parse(uploadFileRes.data);
                            if (responseData.flag) { // 假设接口返回 flag 表示成功
								if (type === 'wechat') 
								{
									that.wxImg = true
                                    that.baseFormData.wechatQrCode = responseData.data;
                                } else {
									that.apImg = true
                                    that.baseFormData.alipayQrCode = responseData.data;
                                }
                                uni.showToast({
                                    title: '上传成功',
                                    icon: 'success'
                                });
                            } else {
                                uni.showToast({
                                    title: '上传失败',
                                    icon: 'none'
                                });
                            }
                        },
                        fail: (err) => {
                            uni.showToast({
                                title: '上传失败',
                                icon: 'none'
                            });
                        }
                    });
                }
            });
        }
    }
};
</script>
<style scoped>
.container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
}
	 .link {
	    text-decoration: underline;
	    color:  #742305;;
	    cursor: pointer; /* 将鼠标指针变为手指形状，表示点击 */
	  }
.form {
    width: 80%;
    margin-bottom: 30px;
    /* display: flex;
  flex-direction: column;
  align-items: center; */
}
uni-easyinput {
    width: 100%;
    height: 80rpx;
    padding: 0 20rpx;
    border: 1px solid #ccc;
    border-radius: 5rpx;
    margin-bottom: 20rpx;
}
.captcha-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 90%;
}
.yzm {
    width: 60%;
    height: 35px;
    margin-right: -1px;
    font-size: 12px;
    position: absolute;
    top: 1px;
    color: black;
    right: 0;
}
.zc {
    width: 100%;
    height: 45px;
    color: #fff;
    border: none;
    border-radius: 4px;
    background-color: #742305;
    font-size: alter;
}
.error-message {
    color: red;
    font-size: 14px;
    margin-top: 5px;
}
.go {
    color: #742305;
    position: absolute;
    top: 5px;
    left: 260px;
}
.ty {
    text-align: center;
    color: darkgray;
    position: absolute;

    left: 70px;
    top: 5px;
}
.upload-container {
    display: flex;
    justify-content: center;
    width: 100%;
}

.preview-image {
    width: 200rpx;
    height: 200rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
}

.upload-area {
    width: 200rpx;
    height: 200rpx;
    border: 2rpx dashed #ddd;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fafafa;
    cursor: pointer;
}

.plus-icon {
    width: 60rpx;
    height: 60rpx;
    position: relative;
}

.plus-icon::before,
.plus-icon::after {
    content: '';
    position: absolute;
    background-color: #ddd;
}

.plus-icon::before {
    width: 4rpx;
    height: 60rpx;
    left: 50%;
    transform: translateX(-50%);
}

.plus-icon::after {
    width: 60rpx;
    height: 4rpx;
    top: 50%;
    transform: translateY(-50%);
}

.info-text {
    height: 80rpx;
    line-height: 80rpx;
    font-size: 28rpx;
    color: #333;
}

.underline {
    border-bottom: 1px solid #ddd;
    min-width: 200rpx;
    padding: 0 20rpx;
}

/* 如果需要调整表单项的样式，可以添加以下样式 */
:deep(.uni-forms-item__content) {
    display: flex;
    align-items: center;
}
</style>
